import cv2
from PIL import Image
import requests
import subprocess
from datetime import datetime
import ntplib


def get_public_ip():
    api_urls = [
        'https://api.ipify.org?format=json',
        'https://ipinfo.io/json',
        'https://icanhazip.com'
    ]
    for api_url in api_urls:
        try:
            response = requests.get(api_url, timeout=5)
            response.raise_for_status()
            if api_url == 'https://api.ipify.org?format=json':
                return response.json()['ip']
            elif api_url == 'https://ipinfo.io/json':
                return response.json()['ip']
            elif api_url == 'https://icanhazip.com':
                return response.text.strip()
        except requests.RequestException as e:
            print(f"尝试从 {api_url} 获取外网 IP 地址时出错: {e}")
    print("所有 API 都无法获取外网 IP 地址。")
    return None


def get_network_connection_type():
    try:
        result = subprocess.run(['netsh', 'interface','show', 'interface'], capture_output=True, text=True)
        output = result.stdout
        if '以太网' in output:
            return '网线'
        elif 'WLAN' in output:
            return 'WiFi'
        return '未知连接方式'
    except Exception as e:
        print(f"获取网络连接方式时出错: {e}")
        return '未知连接方式'


def get_time():
    try:
        # 尝试通过 NTP 服务器获取时间
        ntp_client = ntplib.NTPClient()
        response = ntp_client.request('pool.ntp.org')
        time = datetime.fromtimestamp(response.tx_time)
        return time, '互联网获取时间'
    except ntplib.NTPException as e:
        print(f"通过互联网获取时间时出错: {e}，将使用本地时间。")
        # 若互联网获取失败，使用本地时间
        return datetime.now(), '本地获取时间'


def take_snapshot(save_directory):
    try:
        time, time_source = get_time()
        current_time = time.strftime("%Y%m%d%H%M%S")
        # 修改这里的参数为 1，表示使用第二个摄像头
        video_capture = cv2.VideoCapture(1)
        ret, frame = video_capture.read()
        video_capture.release()

        if ret:
            public_ip = get_public_ip()
            if not public_ip:
                public_ip = '无IP信息'
            connection_type = get_network_connection_type()

            image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img_pil = Image.fromarray(image)
            save_path = f"{save_directory}{time_source}{current_time}_{public_ip}_{connection_type}_snapshot.jpg"
            img_pil.save(save_path)
            print(f"图像已保存到: {save_path}")
        else:
            print("未能捕获到图像。")
    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == "__main__":
    save_directory = "C:\\wap\\photo\\"
    take_snapshot(save_directory)
